<template>
	<div class="main">
		<div class="list" v-if="isList(this.$route.params.newsId)">
			<div class="get-params" v-if="getparams(this.$route.params.category)"></div>
			<div v-for="(item, index) in list">
				<news1 v-if="isFirst(index)" :item="item"></news1>
				<news2 v-else :item="item"></news2>
				<div v-if="!isLast(index)" class="dashed"></div>
			</div>
			<div class="loadmore" @click="loadmoreClick">{{loadmoreText}}</div>
		</div>
		<router-view v-else></router-view>
	</div>
</template>

<script>
	import { mapState, mapMutations, mapActions } from 'vuex'
	import $ from 'jquery'
	import store from '@/store'
	import News1 from '@/components/main/news1'
	import News2 from '@/components/main/news2'

	export default {
		name: 'list',
		data() {
			return {
				category: '',
				isListFlag: true,
				routeChange: false,
				timer: ''
			}
		},
		components: {
			news1: News1,
			news2: News2
		},
		computed: {
			...mapState({
				currentMenu: state => state.MenuStore.currentMenu,
				list: state => state.ListStore.list,
				page: state => state.ListStore.page,
				hasNext: state => state.ListStore.hasNext,
				loadmoreText: state => state.ListStore.loadmoreText
			})
		},
		methods: {
			...mapMutations([

			]),
			...mapActions([
				"getListData", "refreshListData", "loadListData"
			]),
			isFirst: function(index) {
				if(index == 0) {
					return true
				}
				return false
			},
			isLast: function(index) {
				if(index == this.list.length - 1) {
					return false
				}
				return false
			},
			isList: function(id) {
				if(id == null) {
					this.isListFlag = true
					if(this.routeChange) {
						this.getData()
						this.routeChange = false
					}
					return true
				}
				this.isListFlag = false
				return false
			},
			getparams: function(param) {
				store.commit("selectMenu", param)
				this.category = param
				return param
			},
			getData: function() {
				if(!this.isListFlag) {
					return
				}
				store.commit("setLoadMoreText", "正在加载...")
				if(this.currentMenu.url == null) {
					var _this = this
						_this.timer = setTimeout(() => {
							_this.getData()
						}, 50)
						return
				}
				this.refreshListData(this.currentMenu.url)
			},
			observescroll: function() {
				this.scroll = document.documentElement.scrollTop + document.body.scrollTop
				//console.log(this.scroll, parseInt($(window).height()), parseInt($(document).height()))
				if(parseInt($(document).height()) - this.scroll - parseInt($(window).height()) < 300) {
					if(this.isListFlag && this.hasNext && this.page < 5) {
						this.loadListData(this.currentMenu.url)
					}
				}
			},
			loadmoreClick: function() {
				this.loadListData(this.currentMenu.url)
			}
		},
		mounted: function() {
			this.getData()
			window.addEventListener('scroll', this.observescroll)
		},
		watch: {
			'$route' (to, from) {
				this.routeChange = true
			}
		}
	}
</script>